<template>
  <n-modal v-model:show="isVisible" title="编辑类别" preset="dialog" @close="onClose"@update:show="onClose" style="height: 400px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="上级分类：" path="name">
          <n-cascader
              v-model:value="form.parentCategoryName"
              style="width:160px"
              size="small"
              :options="option"
              filterable
          >
          </n-cascader>
        </n-form-item>
      </div>
      <div class="form-row">
        <n-form-item label="分类名称：" path="name">
          <n-input v-model:value="form.name" placeholder="请输入分类名称"/>
        </n-form-item>
      </div>
      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">更新</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
  import {onMounted, ref, watch} from 'vue';
  import { useUserStore } from "@/store/index.js";
  import api from '@/api/admin.js';
  import { List } from "echarts";

  const userStore = useUserStore();
  const id = userStore.getId();
  const option = ref([]);
  const emit = defineEmits(['updatePage']);
  const props = defineProps({
    show1: {
      type: Boolean,
      required: true,
    },
    onClose: {
      type: Function,
      required: true,
    },
    productCategory: {
      type: Object,
      required: true,
    }
  });

  const isVisible = ref(props.show1);
  watch(() => props.show1, (newVal) => {
    isVisible.value = newVal;
    if (newVal) {
      form.value = { ...props.productCategory };
      console.log(props.productCategory.id);
    }
  });

  const form = ref({
    parentCategoryName:'',
    name:'',
  });

  const handleSubmit = async () => {
    try {
      const res = await api.updateProductCategory(form.value);  // 调用更新接口
      if (res.code === 200) {
        emit("updatePage");
      } else {
        $message.error(res.message);
      }
    } catch (err) {
      $message.error("更新失败！");
    } finally {
      clear();
      props.onClose();
    }
  };
  const queryAllProductCategory = async  () => {
    try {
      const res = await api.findAllProductCategory()
      if(res.code === 200) {
        // 调用函数生成n-cascader的options
        convertToCascaderOptions(res.data);
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取产品失败！")
    }finally{
      loading.value = false
    }
  }
  const convertToCascaderOptions = (flatData) => {
    const idNodeMap = {}; // 用于映射id到对应的节点对象
    const opt = []; // 最终生成的级联选择器数据
    // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
    flatData.forEach(node => {
      idNodeMap[node.id] = { ...node, children: [] };
    });
    // 构建树形结构
    Object.values(idNodeMap).forEach(node => {
      if (node.parentCategoryId === null) {
        // 如果parentId为null，则该节点是根节点
        opt.push(node);
      } else {
        // 否则，将该节点添加到其父节点的children数组中
        const parentNode = idNodeMap[node.parentCategoryId];
        if (parentNode) {
          parentNode.children.push(node);
        }
      }
    });
    console.log(opt)
    // 遍历并转换所有根节点
    option.value = opt.map(node=>{
      return traverse(node)
    });
  }
  // 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
  const traverse = (node) => {
    const { id, name, children } = node;
    // 如果children数组为空，则不返回children字段
    const processedNode = {
      value: id.toString(),
      label: name,
      ...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
    };
    return processedNode;
  };
  // 使用optionsForNCascader作为n-cascader的options
  const clear = () => {
    form.value = {
      parentCategoryId:'',
      name:'',
    };
  };
  onMounted(()=>{
    queryAllProductCategory()
  })
</script>

<style scoped>
    .form-container {
        display: flex;
        flex-direction: column;
        width: 100%;
        position: relative;
    }

    .form-row {
        display: flex;
        align-items: center;
        width: 100%;
    }

    .form-row > n-form-item {
        flex: 1;
    }

    .submit-row {
        justify-content: center;
        display: flex;
        width: 100%;
    }
</style>
